<?php

//This is for configuration of wpsary



//get actions
function wpsary_adminPage() {
	switch($_REQUEST['action']) {
		case 'admin':
			wpsary_viewAdmin();
			break;
		case 'deleteimage':
			wpsary_deleteImage($_REQUEST['id'], $_REQUEST['albumID']);
			break;
		case 'viewimage':
			wpsary_listImages($_REQUEST['albumID']);
			break;
		case 'savealbum':
			wpsary_saveAlbum($_POST['albumID']);
			break;
		case 'saveimage':
			if($_POST['delete']) {
				wpsary_deleteImage($_REQUEST['id'], $_REQUEST['albumID']);
			} else {
				wpsary_saveImage($_POST['albumID'], $_POST['id']);
			}
			break;
		case 'deletealbum':
			wpsary_deleteAlbum($_GET['albumID']);
			break;
		case 'addalbum':
		case 'editalbum':
			wpsary_createAlbum($_REQUEST['albumID']);
			break;
		case 'editimage':
		case 'addimage':
				wpsary_uploadImage($_REQUEST['albumID'], $_REQUEST['id']);
			break;
		case 'list':
		default:
			if(get_option('wpsary_activated') == false) {
				wpsary_viewAdmin();
			} else {
				wpsary_listAlbums();
			}
		break;
	}
}

function wpsary_viewAdmin() {
	if($_POST['wpsary_update']) {
		
		update_option('wpsary_pagetitle', $_POST['wpsary_pagetitle']);
		update_option('wpsary_baseurl', trim($_POST['wpsary_baseurl']));
		if((int) $_POST['wpsary_thumbwidth'] > 0 )
			( update_option('wpsary_thumbwidth', (int) $_POST['wpsary_thumbwidth']));
		if((int) $_POST['wpsary_colnumbers'] > 0 )
			( update_option('wpsary_colnumbers', (int) $_POST['wpsary_colnumbers']));
		if((int) $_POST['wpsary_thumbheight'] > 0) 
			(update_option('wpsary_thumbheight',  (int) $_POST['wpsary_thumbheight']));
		update_option('wpsary_activated', true);
?>
		<div id="message" class="updated fade"><p><strong><?php _e('Options saved.', 'wpsary') ?></strong></p></div>
<?php
	}
?>

		<div class = "wrap">
		<h2><?php _e('Photo gallery configuration', 'wpsary') ; ?></h2>
		<form  method="post" action="<?php echo get_option('siteurl') . "/wp-admin/admin.php?page=wpsary"; ?>">
		<input type="hidden" name="action" value="admin" />
		<table width="100%" cellspacing="2" cellpadding="5" class="editform">
		
		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_pagetitle"><?php _e('Page Title', 'wpsary'); ?>:</label></th>
		<td>
		<input name="wpsary_pagetitle" type="text" id="wpsary_pagetitle" value="<?php echo get_option('wpsary_pagetitle') ;?>"  style="width: 350px"/>
		</td>
		</tr>
		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_baseurl"><?php _e('Desired path for your gallery', 'wpsary'); ?>:</label></th>
		<td><?php echo get_bloginfo('url') ;?>/<span style="color: red; font-weight: bold;"><?php echo get_option('wpsary_baseurl') ;?></span><br />
		<input name="wpsary_baseurl" type="text" id="wpsary_baseurl" value="<?php echo get_option('wpsary_baseurl') ;?>"  style="width: 350px"/>
		</td>
		</tr>
		
		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_thumbwidth"><?php _e('Width of thumbnails', 'wpsary'); ?>:</label></th>
		<td>
		<input name="wpsary_thumbwidth" type="text" id="wpsary_thumbwidth" value="<?php echo get_option('wpsary_thumbwidth') ;?>"  style="width: 350px"/>
		</td>
		</tr>

		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_thumbheight"><?php _e('Height of thumbnails', 'wpsary'); ?>:</label></th>
		<td>
		<input name="wpsary_thumbheight" type="text" id="wpsary_thumbheight" value="<?php echo get_option('wpsary_thumbheight') ;?>"  style="width: 350px"/>
		</td>
		</tr>

		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_colnumbers"><?php _e('Number of columns', 'wpsary'); ?>:</label></th>
		<td>
		<input name="wpsary_colnumbers" type="text" id="wpsary_colnumbers" value="<?php echo get_option('wpsary_colnumbers') ;?>"  style="width: 350px"/>
		</td>
		</tr>
		
		</table>
		<p class="submit">
		<input type="submit" name="wpsary_update" value="<?php _e('Save', 'wpsary') ; ?>" />
		</p>
		</form>
		</div>
	<?php
}
function wpsary_deleteImage($id, $albumID = '') {
	global $wpdb;
	if($image = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "wpsary_images WHERE id='$id'")) {
		//remove from db
		$wpdb->query("DELETE FROM " . $wpdb->prefix . "wpsary_images WHERE id='$id'");
		//remove file
		$dir = wpsary_getUploadDir();
		$metadata = wpsary_maybe_unserialize($image->metadata);
		@unlink($dir['path'] . $metadata['file']);
		@unlink($dir['path'] . $metadata['thumb']);
		?>

		<div id="message" class="updated fade"><p><strong> <?php _e('Image successfully deleted', 'wpsary') ?></strong></p></div>
		<?php
		wpsary_listImages($albumID);
	} else {
		wp_die( __('No image to delete') , 'wpsary');
	}
}

function wpsary_saveImage($albumID, $id) {
		global $wpdb;
		
		if ( !current_user_can( 'upload_files' ) )
			wp_die( __('You are not allowed to upload files.', 'wpsary')
				. " <a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary'>"
				. __('Browse Files', 'wpsary') . '</a>'
			);

			$uploaddirarray = wpsary_getUploadDir();
			$uploaddir = $uploaddirarray['path'];
			$uploadfile = $uploaddir.$_FILES['image']['name']; 
			$overrides = array('test_form' => false);
			if($file = wpsary_handle_upload($_FILES['image'], $overrides)) {

				

				if(trim($_POST[title]) == "") {
					$_POST[title] = $file[filename];
				}
				
				$metadata_clause = "";
				$metadata = array();
				if(!$file['error']) {
					$imagesize = getimagesize($file[file]);
					$metadata['width'] = $imagesize['0'];
					$metadata['height'] = $imagesize['1'];
					list($uwidth, $uheight) = get_udims($metadata['width'], $metadata['height']);
					$metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
					$metadata['file'] = $file[filename];

					if ( $metadata['width'] * $metadata['height'] < 3 * 1024 * 1024 ) {
						if ( $metadata['width'] > get_option('wpsary_thumbwidth') && $metadata['width'] >= $metadata['height'] * 4 / 3 )
							$thumb = wp_create_thumbnail($file[file], get_option('wpsary_thumbwidth'));
						elseif ( $metadata['height'] > get_option('wpsary_thumbheight') )
							$thumb = wp_create_thumbnail($file[file], get_option('wpsary_thumbheight'));

						if ( @file_exists($thumb) )
							$metadata['thumb'] = basename($thumb);
					}
					$metadata_clause = " metadata = '" . $wpdb->escape(wpsary_maybe_serialize($metadata)) . "'," ;
				}
				
				if($wp_image = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "wpsary_images WHERE id='$id'")) {
					$query = "UPDATE " . $wpdb->prefix . "wpsary_images SET " .
					" title = '" . $wpdb->escape($_POST[title]) . "'," . 
					" description = '" . $wpdb->escape($_POST[description]) . "'," . 
					$metadata_clause . 
					" albumID = '" . $wpdb->escape($_POST[albumID]) . "' " . 
					" WHERE id='$id'";
				} else {
					$query = "INSERT INTO " . $wpdb->prefix . "wpsary_images " .
					" (title, description, albumID, metadata) VALUES ('" . $wpdb->escape($_POST[title]) . "','" . $wpdb->escape($_POST[description]) . "','" . $wpdb->escape($_POST[albumID]) . "', '" . $wpdb->escape(wpsary_maybe_serialize($metadata)) . "')";
				}
				
				if($wpdb->query($query)) {
				?>
				<div id="message" class="updated fade"><p><strong> <?php _e('Image successfully uploaded', 'wpsary') ?></strong></p></div>
				<?php
					wpsary_listImages($albumID);
					return;
				}else {

				?>
				<div class = "wrap">
				<h2><?php _e('Upload image', 'wpsary') ; ?></h2>
				<?php _e('Unknown error during upload', 'wpsary') ; ?>
				</div>
				<?php
					return;
				}

			} else {
				?>
				<div class = "wrap">
				<h2><?php _e('Upload image', 'wpsary') ; ?></h2>
				<?php _e('Image could not be uploaded.', 'wpsary') ; ?>
				</div>
				<?php
					return;
			} 

			
}


function wpsary_deleteAlbum($albumID) {
	global $wpdb;
?>
<?php
	if(wpsary_getImageList($albumID)) {
	?>
	<div class = "wrap">
	<h2><?php _e('Delete gallery', 'wpsary') ; ?></h2>
	<?php _e('The gallery is not empty. You cannot delete it. Please delete all images inside.', 'wpsary') ; ?>
	</div>
	<?php
		return;
	}

	$query = "DELETE FROM " .$wpdb->prefix . "wpsary_album WHERE id='" . $albumID . "'";
	
	$result = $wpdb->query($query);
	
	?>
	<div id="message" class="updated fade"><p><strong> <?php _e('Gallery deleted', 'wpsary') ?></strong></p></div>
	<?php
	wpsary_listAlbums();
}

function wpsary_getImageList($albumID) {
	global $wpdb;
	$image_table_name = $wpdb->prefix . "wpsary_images";
	if($wpdb->get_var("show tables like '$image_table_name'") != $image_table_name) {
		Return false;
	}

	$query = "SELECT * FROM ".$image_table_name. " WHERE albumID='$albumID'";
	$result = $wpdb->get_results($query);

	Return $result;

}
function wpsary_saveAlbum($albumID = '') {
	global $wpdb;

	$album_table_name = $wpdb->prefix . "wpsary_album";
	if($wpdb->get_var("show tables like '$album_table_name'") != $album_table_name) {
		wpsary_install();
	}
	
	$wpsary_albumtitle = $_POST['wpsary_albumtitle'];
	$wpsary_albumdescription = $_POST['wpsary_albumdescription'];

	$metadata = array();

	if(trim($albumID) == '') {
	//new album
		$query = "INSERT INTO ".$album_table_name." (title, description) VALUES ('" . $wpdb->escape($wpsary_albumtitle) . "', '" . $wpdb->escape($wpsary_albumdescription) . "')";
	} else {
		$albumID = intval($albumID);
		$query = "UPDATE ".$album_table_name." SET title='" . $wpdb->escape($wpsary_albumtitle) . "', description='" .  $wpdb->escape($wpsary_albumdescription) . "' WHERE id='" . $albumID . "'";
	}
	
	$wpdb->query($query);
?>
	<div id="message" class="updated fade"><p><strong> <?php _e('New gallery added succesfully', 'wpsary') ?></strong></p>
	</div>
<?
	wpsary_listAlbums();
}

function wpsary_createAlbum($albumID = '') {
//form
	global $wpdb;
		$dir = wpsary_getUploadDir();


		if(trim($albumID) != '') {
			$album = wpsary_getAlbumInfo($albumID);
			
			if($_REQUEST['setcover']) {
				$setcover = (int)$_REQUEST['setcover'];
				$tmp = $wpdb->get_var("SELECT metadata FROM " . $wpdb->prefix . "wpsary_images WHERE id='$setcover'");
				$imagemetadata = wpsary_maybe_unserialize($tmp);
				$albummetadata = $album->metadata;
				$albummetadata['thumb'] = $imagemetadata['thumb'];
				$albummetadata['hwstring_small'] = $imagemetadata['hwstring_small'];

				$query = $wpdb->query("UPDATE " .$wpdb->prefix . "wpsary_album SET metadata = '" . $wpdb->escape(wpsary_maybe_serialize($albummetadata)) . "' WHERE id='$albumID'");
				$album->metadata = $albummetadata;
			}
			

		}
		
?>
		<div class = "wrap">
		<h2><?php echo ($albumID) ? __('Edit gallery') : __('Add new gallery', 'wpsary') ; ?></h2>
		<form  enctype="multipart/form-data"  method="post" action="<?php echo get_option('siteurl') . "/wp-admin/admin.php?page=wpsary"; ?>">
		<input type="hidden" name="action" value="savealbum" />
		<input type="hidden" name="albumID" value="<?php echo $album->id ; ?>" />
		<table width="100%" cellspacing="2" cellpadding="5" class="editform">
		
		
		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_albumtitle"><?php _e('Album Title', 'wpsary'); ?>:</label></th>
		<td>
		<input name="wpsary_albumtitle" type="text" id="wpsary_albumtitle" value="<?php echo htmlentities(stripslashes($album->title), ENT_QUOTES) ;?>"  style="width: 350px"/>
		</td>
		</tr>

		<tr align="left" valign="top">
		<th scope="row"><label for="wpsary_albumdescription"><?php _e('Description', 'wpsary'); ?>:</label></th>
		<td>
		<textarea name="wpsary_albumdescription" id="wpsary_albumdescription" style="width: 350px"><?php echo htmlentities(stripslashes($album->description), ENT_QUOTES); ?></textarea>
		</td>
		</tr>

		<?php if($album->metadata['thumb']) { ?>
		<tr align="left" valign="top">
		<th scope="row"><?php _e('Album cover', 'wpsary'); ?>:</th>
		<td>
		<img src="<?php echo $dir['url'] . $album->metadata['thumb']  ;?>"/>
		</td>
		</tr>
		<?php } ?>
		
		</table>
		<p class="submit">
		<input type="submit" name="wpsary_savealbum" value="<?php _e('Save', 'wpsary') ; ?>" />
		</p>
		</form>
		</div>

<?

	wpsary_listImages($albumID);
}

function wpsary_listImages($albumID = '') {
	if(trim($albumID) == '') {
		Return false;
	}

	if($images = wpsary_getImageList($albumID)) {
?>
	<script language="JavaScript">
	<!--
	function deleteSomething(msg) {
		if (confirm(msg))
		{
			return true;
		} else {
			return false;
		}
	}
	//-->
	</script>

		<div class="wrap">
			<h2><?php echo __('Images in the album') . " (<a href='"  . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=addimage&albumID=$albumID'>" . __('Add new', 'wpsary') . "</a>)"; ?></h2>
	<table width="100%" cellspacing="2" cellpadding="5">
	<thead>
	<tr>
        <th scope="col"><?php _e('Name', 'wpsary') ?></th>
        <th scope="col"><?php _e('Description', 'wpsary') ?></th>
        <th scope="col" width="90" style="text-align: center"><?php _e('Image', 'wpsary') ?></th>
        <th scope="col" width="90" style="text-align: center" colspan="4"><?php _e('Action', 'wpsary') ?></th>
	</tr>
	</thead>
<?php
		$dir = wpsary_getUploadDir();

		foreach($images as $image) {
		$metadata = wpsary_maybe_unserialize($image->metadata)
?>
		<tr scope="row">
			<td valign="top">
				<?php echo stripslashes($image->title); ?>
			</td>
			<td valign="top">
				<?php echo stripslashes(nl2br($image->description)); ?>
			</td>
			<td valign="top">
				<?php echo "<a href=\"" . $dir['url'] . $metadata['file'] . "\" target=\"_blank\"><img src=\"" . $dir['url'] . $metadata['thumb'] . "\" " . $metadata['hwstring_small'] . " border=\"0\" /></a>"; ?>
			</td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=editalbum&setcover=" . $image->id . "&albumID=" . $image->albumID . "'>" . __('Album cover', 'wpsary') . "</a>"; ?>
		  </td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=editimage&id=" . $image->id . "&albumID=" . $image->albumID . "'>" . __('Edit', 'wpsary') . "</a>"; ?>
		  </td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=deleteimage&id=" . $image->id . "&albumID=" . $image->albumID. "' onclick=\"return deleteSomething('" . addslashes(__('You are about to delete this image. \'OK\' to delete, \'Cancel\' to stop.')) . "');\">" . __('Delete', 'wpsary') . "</a>"; ?>
		  </td>
		</tr>
<?php
		}
?>
	</tr>
	</table>
<?php
	} else {
?>
		<div class = "wrap">
		<h2><?php _e('No image found', 'wpsary') ;?></h2>
		<p> <?php echo "<a href='"  . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=addimage&albumID=$albumID'>" . __('Upload new image', 'wpsary') . "</a>"; ?></p>
		</div>
<?php
		return;
		
	}
}
function wpsary_listAlbums() {
	global $user_ID;
	$albums = wpsary_getAlbumList();
?>

		<div class = "wrap">
		<p> <?php echo "<a href='"  . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=admin'>" . __('Go to configuration', 'wpsary') . "</a>"; ?></p>
		</div>
<?php
	
	if(!$albums) {
?>

		<div class = "wrap">
		<h2><?php _e('No gallery found', 'wpsary') ;?></h2>
		<p> <?php echo "<a href='"  . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=addalbum'>" . __('Add new gallery', 'wpsary') . "</a>"; ?></p>
		</div>
<?php
		return;
	}

?>
	<script language="JavaScript">
	<!--
	function deleteSomething(msg) {
		if (confirm(msg))
		{
			return true;
		} else {
			return false;
		}
	}
	//-->
	</script>
		<div class = "wrap">
		<h2><?php echo __('Photo Gallery') . " (<a href='"  . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=addalbum'>" . __('Add new', 'wpsary') . "</a>)"; ?></h2>

<table class="widefat">
	<thead>
	<tr>
        <th scope="col"><?php _e('Name', 'wpsary') ?></th>
        <th scope="col"><?php _e('Description', 'wpsary') ?></th>
        <th scope="col" width="90" style="text-align: center"><?php _e('Images', 'wpsary') ?></th>
        <th scope="col" width="90" style="text-align: center" colspan="3"><?php _e('Action', 'wpsary') ?></th>
	</tr>
	</thead>
	<tbody id="the-list">
	<?php foreach($albums as $album) 
		{ 
		$i++;
		$alternate = ($i % 2 == 0) ? "alternate": "";
	?>
		<tr scope="row" class="<?php echo $alternate; ?>">
		  <td valign=top style="width: 100px">
		   <?php echo stripslashes($album->title) ?>
		  </td>
		  <td valign=top>
		   <?php echo stripslashes($album->description) ?>
		  </td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=viewimage&albumID=" . $album->id . "'>" . __('View', 'wpsary') . "</a>"; ?>
		  </td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=editalbum&albumID=" . $album->id . "'>" . __('Edit', 'wpsary') . "</a>"; ?>
		  </td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=addimage&albumID=" . $album->id . "'>" . __('Add image', 'wpsary') . "</a>"; ?>
		  </td>
		  <td valign=top>
		   <?php echo "<a href='" . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=deletealbum&albumID=" . $album->id . "' onclick=\"return deleteSomething('" . addslashes(__('You are about to delete this gallery. \'OK\' to delete, \'Cancel\' to stop.')) . "');\">" . __('Delete', 'wpsary') . "</a>"; ?>
		  </td>
		</tr>
	<?php 
		}
	?>
	</tbody>
</table>
</div>
<?php
}


function wpsary_uploadImage($albumID, $id) {
	global $wpdb;
	$id			= (int) $id;
	$albumID	= (int) $albumID;
	
	$albums = wpsary_getAlbumList();
	if(!$albums) {
?>
		<div class = "wrap">
		<h2><?php _e('No gallery found', 'wpsary') ;?></h2>
		<p> <?php echo __('Before uploading an image, create a new gallery.') . "<br/><a href='"  . get_option('siteurl') . "/wp-admin/admin.php?page=wpsary&action=addalbum'>" . __('Add new gallery', 'wpsary') . "</a>"; ?></p>
		</div>
<?php
		return;
	}

	$wp_image = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "wpsary_images WHERE id='" . $id . "'");
	$id = $wp_image->id
?>	
	<div class="wrap">
	<h2><?php echo $id ? __('Edit image') : __('Upload new image', 'wpsary') ; ?></h2>
	<form enctype="multipart/form-data"  id="upload-file" method="post" action="<?php echo get_option('siteurl') . "/wp-admin/admin.php?page=wpsary" ?>">
		<input type='hidden' name='id' value="<?php echo $wp_image->id;?>">
		<input type='hidden' name='action' value="saveimage">
		<table><col /><col class="widefat" />
			<tr>
				<th scope="row"><label for="title"><?php _e('Title', 'wpsary'); ?></label></th>
				<td><input type="text" id="title" name="title" value="<?php echo htmlentities(stripslashes($wp_image->title), ENT_QUOTES); ?>"  style="width: 350px"/></td>
			</tr>
			<tr>
				<th scope="row"><label for="albumID"><?php _e('Album', 'wpsary'); ?></label></th>
				<td><select id="albumID" name="albumID" style="width: 350px">
				<?php
					foreach($albums as $album) {
						$selected = ($album->id == $albumID || $album->id == $wp_image->albumID) ? " selected ": "";
						echo "<option value=\"" . $album->id . "\" $selected>" . stripslashes($album->title) . "</option>";
						
					} 
				?>
					
					</select></td>
			</tr>
			<tr>
				<th scope="row"><label for="upload"><?php _e('Image', 'wpsary'); ?></label></th>
				<td><input type="file" id="image" name="image" style="width: 350px"/></td>
			</tr>
			<tr>
				<th scope="row"><label for="description"><?php _e('Description', 'wpsary'); ?></label></th>
				<td><textarea name="description" id="description"  style="width: 350px"><?php echo stripslashes($wp_image->description); ?></textarea></td>
			</tr>
			<tr id="buttons" class="submit">
				<td colspan='2'>
<?php	if ( $id ) { ?>
					<input type="submit" name="delete" id="delete" class="delete alignleft" value="<?php _e('Delete image', 'wpsary'); ?>" />
<?php	} ?>
					<input type="submit" name="submit" value="<?php echo $id ? __('Save') : __('Upload', 'wpsary'); ?>" />
				</td>
			</tr>
		</table>
	</form>
	</div>
<?php
}




function wpsary_getAlbumInfo($albumID) {
	global $wpdb;
	if($album = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "wpsary_album WHERE id='$albumID'")) {
		$album->title = stripslashes($album->title);
		$album->description = stripslashes($album->description);
		$album->metadata = wpsary_maybe_unserialize($album->metadata);
		$album->images = wpsary_getImageList($albumID);
		$dir = wpsary_getUploadDir();

		$album->url = $dir[url];

		Return $album;
	} else {
		Return false;
	}
}


function wpsary_getAlbumList() {
	global $wpdb;

	$album_table_name = $wpdb->prefix . "wpsary_album";
	if($wpdb->get_var("show tables like '$album_table_name'") != $album_table_name) {
		Return false;
	}

	$query = "SELECT * FROM ".$album_table_name;
	$result = $wpdb->get_results($query);

	Return $result;

}

function wpsary_getUploadDir() {
      $siteurl = get_option('siteurl');
      //prepend ABSPATH to $dir and $siteurl to $url if they're not already there
      $path = str_replace(ABSPATH, '', trim(get_settings('upload_path')));
      $dir = ABSPATH . $path;
      $url = trailingslashit($siteurl) . $path;
  
      if ( $dir == ABSPATH ) { //the option was empty
          $dir = ABSPATH . 'wp-content/uploads';
      }
  
      if ( defined('UPLOADS') ) {
          $dir = ABSPATH . UPLOADS;
          $url = trailingslashit($siteurl) . UPLOADS;
      }
      
	  $dir .= "/album/";
	  $url .= "/album/";
      // Make sure we have an uploads dir
      if ( ! wp_mkdir_p( $dir ) ) {
          $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $dir, 'wpsary');
          return array('error' => $message);
      }
  
      $uploads = array('path' => $dir, 'url' => $url, 'error' => false);
      return $uploads;
}

// On success, returns an associative array of file attributes.
// On failure, returns  array( 'error'=>$message ).
function wpsary_handle_upload( &$file ) {
	// The default error handler.
	if (! function_exists( 'wpsary_handle_upload_error' ) ) {
		function wpsary_handle_upload_error( &$file, $message ) {
			return array( 'error'=>$message );
		}
	}

	// A properly uploaded file will pass this test. There should be no reason to override this one.
	if (! @ is_uploaded_file( $file['tmp_name'] ) )
		return wpsary_handle_upload_error( $file, __( 'Specified file failed upload test.' ), 'wpsary');

	// A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
	
	$wp_filetype = wp_check_filetype( $file['name'], $mimes );

	extract( $wp_filetype );

	if ( !$type || !$ext )
		return $wp_check_filetype( $file, __( 'File type does not meet security guidelines. Try another.' ), 'wpsary');

	// A writable uploads dir will pass this test. Again, there's no point overriding this one.
	if ( ! ( ( $uploads = wpsary_getUploadDir() ) && false === $uploads['error'] ) )
		return wpsary_handle_upload_error( $file, $uploads['error'] );

	// Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.

		$number = '';
		$filename = str_replace( '#', '_', $file['name'] );
		$filename = str_replace( array( '\\', "'" ), '', $filename );
		if ( empty( $ext) )
			$ext = '';
		else
			$ext = ".$ext";
		
		while ( file_exists( $uploads['path'] . $filename) ) {
			if ( '' == "$number$ext" )
				$filename = $filename . ++$number . $ext;
			else
				$filename = str_replace( "$number$ext", ++$number . $ext, $filename );
		}
		$filename = str_replace( $ext, '', $filename );
		$filename = $filename . $ext;


	// Move the file to the uploads dir
	$new_file = $uploads['path'] . $filename;
	if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
		wp_die( printf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ), 'wpsary');

	// Set correct file permissions
	$stat = stat( dirname( $new_file ));
	$perms = $stat['mode'] & 0000666;
	@ chmod( $new_file, $perms );

	// Compute the URL
	$url = $uploads['url'] . $filename;
	
	$return = apply_filters( 'wpsary_handle_upload', array( 'filename' => $filename, 'file' => $new_file, 'url' => $url, 'type' => $type ) );

	return $return;
}

function wpsary_getImageInfo($id) {
	global $wpdb;

	if($photo = $wpdb->get_row("SELECT * FROM ". $wpdb->prefix . "wpsary_images WHERE id='$id'")) {
		$photo->metadata = wpsary_maybe_unserialize($photo->metadata);
		
		$photo->title = stripslashes($photo->title);
		$photo->description = stripslashes($photo->description);
		$dir = wpsary_getUploadDir();

		$photo->url = $dir[url];
		Return $photo;
		
	} else {
		Return false;
	}
	
	
}


function wpsary_maybe_serialize($data) {
	if ( is_string($data) )
		$data = trim($data);
	elseif ( is_array($data) || is_object($data) )
		return serialize($data);
	if ( wpsary_is_serialized($data) )
		return serialize($data);
	return $data;
}

function wpsary_is_serialized($data) {
	// if it isn't a string, it isn't serialized
	if ( !is_string($data) )
		return false;
	$data = trim($data);
	if ( 'N;' == $data )
		return true;
	if ( !preg_match('/^([adObis]):/', $data, $badions) )
		return false;
	switch ( $badions[1] ) :
	case 'a' :
	case 'O' :
	case 's' :
		if ( preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data) )
			return true;
		break;
	case 'b' :
	case 'i' :
	case 'd' :
		if ( preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data) )
			return true;
		break;
	endswitch;
	return false;
}

function wpsary_maybe_unserialize($original) {
	if ( wpsary_is_serialized($original) ) // don't attempt to unserialize data that wasn't serialized going in
		if ( false !== $gm = @ unserialize($original) )
			return $gm;
	return $original;
}

?>